package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.*;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.*;
import com.joint.core.service.*;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by root on 16/12/16.
 */
@ParentPackage("com")
public class AjaxTrainAction extends BaseFlowAction {

    @Resource
    private TrainService trainService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private ManageService manageService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private ParticipantService participantService;
    @Resource
    private EmployeesService employeesService;
    @Resource
    private ReadersService readersService;
    @Resource
    private RemindService remindService;
    @Resource
    private TrainRecordService trainRecordService;

    private Train train;
    private Employees employees;
    private Participant participant;
    private String name;
    private List<Map<String, Object>> trainDict;
    private String traindictId;
    private String contentText;
    private String contentfileId;
    private String contentfileIds;
    private String startDate;
    private String endDate;
    private String departmentId;
    private List<Department> departmentList;
   // private String participantId;
    private List<String> participantId;
    private List<Users> participantUsersList;
    private Users loginUser;
    private Users creater;
    private String createDate;
    private String trainUsersName;
    private String trainUsersId;
    private String remark;
    private Set<Participant> participantSet;
    private List<Users> usersList;

    /**
     * 视图类型
     */
    private String viewtype;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "train";
    }

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        //内嵌视图这里要加上
       /* if (StringUtils.isNotEmpty(parentId)){
            employees= employeesService.get(parentId);
            LogUtil.info("+++"+employees.getUsers());
            params.put("employees",employees);
        }*/
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                pager=trainService.findByPagerAndLimit(false, "train", pager, params);
            }else if(viewtype.equals("2")){
                params.put("finish","0");
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=trainService.findByPagerAndFinish( "train", pager, params);

            }else if(viewtype.equals("3")){
                //已归档
                params.put("finish","1");
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=trainService.findByPagerAndFinish( "train", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=trainService.findByPagerAndLimit(true, "train", pager, params);
        }

        List<Train> tList;
        if (pager.getTotalCount() > 0){
            tList = (List<Train>) pager.getList();
        }else{
            tList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Train train:tList){
            rMap = new HashMap<String,Object>();
            rMap.put("name",train.getName());
            rMap.put("id",train.getId());
            rMap.put("type",train.getType()==null?"":train.getType().getName());
            rMap.put("time","从"+DataUtil.DateToString(train.getStartDate(),"yyyy-MM-dd")+"到"+DataUtil.DateToString(train.getEndDate(),"yyyy-MM-dd"));
            rMap.put("time1",DataUtil.DateToString(train.getStartDate(),"yyyy-MM-dd"));
            String state = train.getProcessState().name();
            if(state.equals("Running")){
                rMap.put("state","培训中");
            }else {
                rMap.put("state","已完成");

            }
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 查看
     */
    public String read(){
        contentfileId="";
        participantSet=Sets.newHashSet();

        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            train = trainService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            if(train.getContent().size()>0){
                for(FileManage r:train.getContent()){
                    contentfileId+=r.getId()+",";
                }
            }
            if(train.getParticipantSet()!=null){
                participantSet=train.getParticipantSet();
                for (Participant participant:participantSet){
                     usersList = participant.getParticipantUsers();
                    LogUtil.info("usersList"+usersList);

                }

                LogUtil.info("participantSet"+participantSet);
            }
        }

        return "read";
    }


    /**
     * 培训完成
     */
    public String update(){
        //setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                Train entity =trainService.get(keyId);
                entity.setFinish("1");
                trainService.update(entity);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");

    }


    public String input(){

        loginUser = usersService.getLoginInfo();
        contentfileId="";
        Company company = usersService.getCompanyByUser();
        List<Dict> trainType = dictService.listFormDefinedEnable(DictBean.DictEnum.TrainType, company.getId());
        trainDict = new ArrayList<Map<String, Object>>();

        Map<String,Object> rMap = null;
        if(StringUtils.isNotEmpty(parentId)) {
            train= trainService.get(parentId);
        }
        if (StringUtils.isNotEmpty(keyId)){
            train = trainService.get(keyId);
            if(train.getContent().size()>0){
                for(FileManage r:train.getContent()){
                    contentfileId+=r.getId()+",";
                }
            }

            for(Dict typeObj:trainType){
                rMap = new HashMap<String, Object>();
                rMap.put("id",typeObj.getId());
                rMap.put("name",typeObj.getName());
                rMap.put("selected","");
                LogUtil.info("name"+typeObj.getName());
                if(train.getType()!=null && com.joint.base.util.StringUtils.equals(typeObj.getId(), train.getType().getId())){
                    rMap.put("selected","selected");
                }
                trainDict.add(rMap);
            }
            if(train.getParticipantSet()!=null){
                participantSet=train.getParticipantSet();

                LogUtil.info("participantSet"+participantSet);
            }
            creater=train.getCreater();
            createDate= DataUtil.DateToString(train.getCreateDate(),"yyyy-MM-dd");

        } else {

            for(Dict typeObj:trainType){
                rMap = new HashMap<String, Object>();
                rMap.put("id",typeObj.getId());
                rMap.put("name",typeObj.getName());
                rMap.put("selected","");
                trainDict.add(rMap);
            }
            creater=loginUser;
            createDate= DataUtil.DateToString(new Date(),"yyyy-MM-dd");

        }

        return "input";
    }

    private void setData(){

        departmentList=Lists.newArrayList();
        participantUsersList=Lists.newArrayList();
        participantSet= Sets.newHashSet();
        List<FileManage> fileList = Lists.newArrayList();
        List<Department> departmentList = Lists.newArrayList();
        List<Users> usersList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(keyId)){
            train = trainService.get(keyId);

            Set<Participant> participantSet = train.getParticipantSet();
            if(participantSet.size()>0){
                for (Participant participant:participantSet){
                    String pId = participant.getId();
                    participantService.update(participantService.get(pId));
                }
            }

        }else{
            train = new Train();
            train.setCreater(usersService.getLoginInfo());
        }
        if(StringUtils.isNotEmpty(contentfileIds)){
            for(String r:contentfileIds.split(",")){
                fileList.add(fileManageService.get(r.trim()));
            }
        }

        if(StringUtils.isNotEmpty(departmentId)){
            for (String id:departmentId.split(",")){
                departmentList.add(departmentService.get(id.trim()));
            }
        }

        int len=departmentList.size();
        Participant [] participants=new Participant[len];
        for (int i=0;i<len;i++){
            participants[i] = new Participant();
            participants[i].setDepartment(departmentService.get(departmentList.get(i).getId()));
            String s = participantId.get(i);
            participantUsersList = Lists.newArrayList();
            for(String id:s.split(",")){
                participantUsersList.add(usersService.get(id.trim()));
                participants[i].setParticipantUsers(participantUsersList);
            }
            participantService.save(participants[i]);
            participantSet.add(participants[i]);

        }

        if(StringUtils.isNotEmpty(trainUsersId)){
            for(String id:trainUsersId.split(",")){
                usersList.add(usersService.get(id.trim()));
            }
        }

        if(StringUtils.isNotEmpty(startDate)){
            train.setStartDate(DataUtil.StringToDate(startDate));
        }
        if(StringUtils.isNotEmpty(endDate)){
            train.setEndDate(DataUtil.StringToDate(endDate));

        }
        if(StringUtils.isNotEmpty(traindictId)){
            train.setType(dictService.get(traindictId));
        }

        train.setParticipantSet(participantSet);
        train.setName(name);
        train.setFinish("0");
        train.setContent(fileList);
        train.setContextText(contentText);
        train.setRemark(remark);
        train.setTrainUsers(usersList);
        train.setCompany(usersService.getLoginInfo().getCompany());

    }

    /**
     * 保存
     * @return
     */
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                trainService.update(train);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("initDuty", curDutyId);
                trainService.save(train, "train", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    /**
     * 提交
     * @return
     */
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                trainService.approve(train, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId=trainService.commit(train, "train", var1, var2, curDutyId);

                //trainService.commit(train, FlowEnum.ProcessState.Finished,"train", var1,var2, curDutyId);

            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        List<Users> usersList= Lists.newArrayList();
        Set<Participant> participantSet = train.getParticipantSet();
        for (Participant participant:participantSet){
            usersList = participant.getParticipantUsers();
            //增加归档后读者
            for(Users users:usersList){
                Readers readers = new Readers();
                readers.setUsers(users);
                readers.setBussinessKey("train");
                readers.setKeyId(keyId);
                readers.setType(2);
                readersService.save(readers);
            }

            for(Users users:usersList){
                Remind remind = new Remind();
                remind.setUsers(users);
                remind.setBussinessKey("train");
                remind.setKeyId(keyId);
                remind.setContent("您有一条培训安排,请查阅");
                remindService.save(remind);
            }

        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 审批
     * @return
     */
    public String approve1(){
        train = trainService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                trainService.approve(train, FlowEnum.ProcessState.Finished, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Map<String, Object>> getTrainDict() {
        return trainDict;
    }

    public void setTrainDict(List<Map<String, Object>> trainDict) {
        this.trainDict = trainDict;
    }

    public String getTraindictId() {
        return traindictId;
    }

    public void setTraindictId(String traindictId) {
        this.traindictId = traindictId;
    }

    public String getContentText() {
        return contentText;
    }

    public void setContentText(String contentText) {
        this.contentText = contentText;
    }

    public String getContentfileId() {
        return contentfileId;
    }

    public void setContentfileId(String contentfileId) {
        this.contentfileId = contentfileId;
    }

    public String getStartDate() {
        return startDate;
    }

    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    public String getEndDate() {
        return endDate;
    }

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    public String getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(String departmentId) {
        this.departmentId = departmentId;
    }

    public Train getTrain() {
        return train;
    }

    public void setTrain(Train train) {
        this.train = train;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public Users getCreater() {
        return creater;
    }

    public void setCreater(Users creater) {
        this.creater = creater;
    }

    public String getCreateDate() {
        return createDate;
    }

    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public String getContentfileIds() {
        return contentfileIds;
    }

    public void setContentfileIds(String contentfileIds) {
        this.contentfileIds = contentfileIds;
    }

    public String getTrainUsersName() {
        return trainUsersName;
    }

    public void setTrainUsersName(String trainUsersName) {
        this.trainUsersName = trainUsersName;
    }

    public String getTrainUsersId() {
        return trainUsersId;
    }

    public void setTrainUsersId(String trainUsersId) {
        this.trainUsersId = trainUsersId;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public Participant getParticipant() {
        return participant;
    }

    public void setParticipant(Participant participant) {
        this.participant = participant;
    }

    public List<Department> getDepartmentList() {
        return departmentList;
    }

    public void setDepartmentList(List<Department> departmentList) {
        this.departmentList = departmentList;
    }

    public List<Users> getParticipantUsersList() {
        return participantUsersList;
    }

    public void setParticipantUsersList(List<Users> participantUsersList) {
        this.participantUsersList = participantUsersList;
    }

    public Set<Participant> getParticipantSet() {
        return participantSet;
    }

    public void setParticipantSet(Set<Participant> participantSet) {
        this.participantSet = participantSet;
    }

    public List<Users> getUsersList() {
        return usersList;
    }

    public void setUsersList(List<Users> usersList) {
        this.usersList = usersList;
    }

    public void setParticipantId(List<String> participantId) {
        this.participantId = participantId;
    }
}
